import os

from flask import Flask, render_template, request
from flask import Blueprint
import json
import traceback
import importlib

from applications.common.utils.http import table_api, success_api, fail_api

plugin_bp = Blueprint('plugins', __name__, url_prefix='/plugins')
PLUGIN_ENABLE_FOLDERS = []

this_dir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/')
root_dir = this_dir.replace('applications/view/plugin', '')

def register_plugin_views(app: Flask):
    """初始化插件"""
    app.register_blueprint(plugin_bp)
    # 载入插件过程
    # plugin_folder 配置的是插件的文件夹名

    confjson = root_dir + "etc/plugin/config.json"
    if os.path.exists(confjson):
        with open(confjson, "r", encoding='utf-8') as f:
            plugin_enabled = json.loads(f.read())
    else:
        plugin_enabled = {}
    # 查看是否有dev默认模块，开发版自动加载。
    if os.path.exists(root_dir + "plugins/dev/__init__.json"):
        with open(root_dir + "plugins/dev/__init__.json", "r", encoding='utf-8') as f:
            plugin_enabled['dev'] = json.loads(f.read())
    if plugin_enabled:
        for key in plugin_enabled:
            plugin_dir = root_dir + "plugins/" + plugin_enabled[key]['folder']
            try:
                with open(plugin_dir + "/__init__.json", "r", encoding='utf-8') as f:
                    plugin_info = json.loads(f.read())
                try:
                    getattr(importlib.import_module('plugins.' + plugin_enabled[key]['folder']), "event_init")(app)
                except AttributeError:  # 没有插件启用事件就不调用
                    pass
            except BaseException as e:
                info = f" * Plugin: Crash a error when loading {plugin_info['name'] if len(plugin_info) != 0 else 'plugin'} :" + "\n"
                info += 'str(Exception):\t' + str(Exception) + "\n"
                info += 'str(e):\t\t' + str(e) + "\n"
                info += 'repr(e):\t' + repr(e) + "\n"
                info += 'traceback.format_exc():\n%s' + traceback.format_exc()
                print(info)

@plugin_bp.route('/', methods=['GET'])
def index():
    return render_template('plugins/index.html')

@plugin_bp.route('/data', methods=['GET'])
def data():
    confjson = "etc/plugin/config.json"
    if os.path.exists(confjson):
        plugin_enabled = json.load(open('etc/plugin/config.json', 'r', encoding='utf-8'))
    else:
        plugin_enabled = {}
    actkeys = plugin_enabled.keys()
    plugins = os.listdir('plugins')
    rt = []
    for plugin in plugins:
        if plugin in ['__pycache__','dev']:
            continue
        installedkey = 'etc/plugin/'+plugin+'.lock'

        if os.path.isdir('plugins/' + plugin):
            with open('plugins/' + plugin + '/__init__.json', 'r', encoding='utf-8') as f:
                info = json.load(f)
            # 检查是否发行（打过包）
            if 'package' not in info:
                continue
            # 检查依赖
            info['dependon'] = 1
            if 'dependencies' in info:
                for dep in info['dependencies'].keys():
                    if dep not in plugins:
                        info['dependon'] = 0
            if os.path.exists(installedkey):
                info['installed'] = 1
                # 是否激活
                if plugin in actkeys:
                    info['enable'] = 1
                else:
                    info['enable'] = 0
            else:
                info['installed'] = 0
                info['enable'] = -1

            rt.append(info)
    return table_api(data=rt, count=len(rt))

@plugin_bp.route('/config', methods=['GET', 'POST'])
def config():
    if request.method == 'POST':
        appdir = request.form.get('appdir')
        configfile = os.path.join('plugins', appdir, 'config', 'config.json')
        if os.path.exists(configfile):
            jsonconf = json.load(open(configfile, 'r', encoding='utf-8'))
            for k in request.form.keys():
                if k in jsonconf:
                    jsonconf[k]['val'] = request.form[k]

            json.dump(jsonconf, open(configfile, 'w', encoding='utf-8'), indent=4, ensure_ascii=False)
            return success_api(msg='配置保存成功')
        else:
            return fail_api(msg='配置文件不存在')


    else:
        appdir = request.args.get('appdir')
        configfile = os.path.join('plugins', appdir, 'config', 'config.json')
        if os.path.exists(configfile):
            jsonconf = json.load(open(configfile, 'r', encoding='utf-8'))
            # print(jsonconf)
            if jsonconf:
                jdata = {'__sys__': {}}
                for k in jsonconf.keys():
                    if '_' in k:
                        tmp = k.split('_')
                        if tmp[0] not in jdata:
                            jdata[tmp[0]] = {}
                        jdata[tmp[0]][k] = jsonconf[k]
                    else:
                        jdata['__sys__'][k] = jsonconf[k]
                # print(jdata)
                return render_template('plugins/config.html', jsonconf=jdata, appdir=appdir)
        else:
            return render_template('plugins/msg.html', msg='配置文件不存在')